<template>
    <teleport to=".header">
        <SdyHeader title="登录" />
    </teleport>
    <div class="login-box">
        <van-form @submit="submitHandler" class="login-form">
            <van-cell-group inset>
                <van-field v-model="userInfo.loginname" name="loginname" label="用户名" placeholder="用户名"
                    :rules="[{ required: true, message: '请填写用户名' }]" />
                <div class="item">
                    <van-field :type="pwdVisited ? 'text' : 'password'" v-model="userInfo.password" name="password"
                        label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]" />
                    <van-icon @click="pwdVisited = false" v-if="pwdVisited" class="eye" name="eye-o" />
                    <van-icon @click="pwdVisited = true" v-else class="eye" name="closed-eye" />
                </div>
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button color="red" round block type="primary" native-type="submit">
                    登录
                </van-button>
            </div>
        </van-form>
        <van-divider :style="{ borderColor: '#999', width: '100%' }">其他</van-divider>

        <p>还没有账号, <router-link to="/register">去注册</router-link></p>
    </div>
</template>

<script name="sdyLogin" lang="ts" setup>
import SdyHeader from '../../components/header.vue'
import { login } from '../../model/users'
import { ref } from 'vue'
import { showSuccessToast, showFailToast } from 'vant'
import { useRouter } from 'vue-router'

const $myRouter = useRouter()


interface User {
    loginname: string
    password: string
}

interface ResponeInfo {
    code: string
    data?: {
        token: string
        userid: string
    },
    message: string
}

// 存储用户信息
const userInfo = ref<User>({ loginname: "", password: '' })

// 密码是否显示
const pwdVisited = ref<boolean>(false)

// 表单提交
const submitHandler = async (info: User) => {
    const res = await login(info)
    console.log(res);
    if ((res as unknown as ResponeInfo).code === '10011') {
        showFailToast('密码错误')
        return
    }
    if ((res as unknown as ResponeInfo).code === '10010') {
        showFailToast('该用户不存在')
        return
    }
    showSuccessToast('登录成功')
    // 将用户信息存储起来
    window.localStorage.setItem('token', res.data.token)
    window.localStorage.setItem('user_id', res.data.userid)
    // 跳转到上一个页面
    $myRouter.back()

}
</script>

<style scoped lang="scss">
.login-box {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    >.login-form {
        border: 1px solid #333;
        border-radius: 10px;

        .item {
            position: relative;

            >.eye {
                position: absolute;
                right: 10px;
                top: 15px;
            }
        }
    }
}
</style>